<template>
  <div class="page page-poetry-detail">
    <div class="poetry-detail-container" v-if="poetryDetail">
      <!-- 返回按钮 -->
      <div class="back-btn" @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </div>
      
      <!-- 诗词标题区域 -->
      <div class="poetry-header">
        <h1 class="poetry-title">{{ poetryDetail.title }}</h1>
        <div class="poetry-meta">
          <span class="dynasty">[{{ poetryDetail.dynasty }}]</span>
          <span class="author">{{ poetryDetail.author }}</span>
        </div>
      </div>
      
      <!-- 诗词原文 -->
      <div class="poetry-content">
        <h2 class="section-title">原文</h2>
        <div class="poetry-original">
          <p v-for="(line, index) in poetryDetail.content.split('。')" :key="'line-' + index">{{ line }}</p>
        </div>
      </div>
      
      <!-- 配图区域 -->
      <div class="poetry-image">
  <h2 class="section-title">配图</h2>
  <div class="image-container">
    <!-- 上半部分：配图按钮 -->
    <div class="image-action">
      <el-button type="primary" icon="Plus" class="create-btn" @click="showPictureDialog = true">
        挑选配图
      </el-button>
    </div>
    
    <!-- 下半部分：配图列表/提示 -->
    <div class="image-list">
      <!-- 有配图时显示轮播 -->
      <template v-if="poetryDetail.workinfos && poetryDetail.workinfos.length > 0">
        <el-carousel 
    :interval="5000" 
    height="400px" 
    arrow="always"
    indicator-position="outside"
    class="poetry-carousel"
  >
    <el-carousel-item v-for="(group, groupIndex) in groupedWorkinfos" :key="'group-' + groupIndex">
      <div class="work-group">
        <div v-for="(work, index) in group" :key="'work-' + work.id" class="work-item">
          <PublicCptWorkInfoItem 
            :workInfo="work" 
            :width="workItemWidth" 
            :showAuthor="true" 
            :showEditMenu="false" 
            :customerClick="true" 
            @customerClick="customerClick"
            @downloadImage="downloadImage"
          />
        </div>
      </div>
    </el-carousel-item>
  </el-carousel>
      </template>
      
      <!-- 无配图时显示提示 -->
      <div v-else class="no-image">
        <el-empty description="暂无配图">
          <template #description>
            <p>暂无配图，快来创作第一幅吧！</p>
          </template>
          <el-button type="primary" @click="router.push('/apps')">前往创作</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</div>
      
      <!-- 白话译文 -->
      <div class="poetry-translation">
        <h2 class="section-title">白话译文</h2>
        <div class="section-content" v-html="poetryDetail.translation">
       
        </div>
      </div>
      
      <!-- 背景 -->
      <div class="poetry-background">
        <h2 class="section-title">背景</h2>
        <div class="section-content" v-html="poetryDetail.background">
         
        </div>
      </div>
      
      <!-- 赏析 -->
      <div class="poetry-appreciation">
        <h2 class="section-title">赏析</h2>
         <div class="section-content" v-html="poetryDetail.appreciation">
          
        </div>
      </div>
    </div>
    
    <!-- 加载中状态 -->
    <div class="loading-container" v-else-if="pending">
      <el-skeleton animated :rows="10" />
    </div>
    
    <!-- 错误状态 -->
    <div class="error-container" v-else-if="error">
      <el-empty description="获取诗词信息失败" :image-size="200">
        <template #description>
          <p>{{ error }}</p>
        </template>
        <el-button type="primary" @click="refresh">重试</el-button>
      </el-empty>
    </div>
  </div>
  <el-image-viewer v-if="showViewer" :url-list="srcList" @close="closePreivew" close-on-press-escape>

</el-image-viewer>
  <!-- 配图选择弹窗 -->
<el-dialog
  v-model="showPictureDialog"
  title="挑选配图"
  width="90%"
  destroy-on-close
  class="picture-select-dialog"
>
  <div class="picture-gallery">
    <!-- 图片网格 -->
    <div class="picture-grid" >
      
        <PublicCptWorkInfoItem :workInfo="work" :width="150" :showAuthor="true" :showEditMenu="false"
        :showToggleIluPoster="true"
        :posterId="poetryId"
        :showFavorMenu="false"
         v-for="(work, index) in pictureList" :key="work.id" 
         @downloadImage="downloadImage"
         @toggleIluPoster="toggleIluPoster"
            >
          </PublicCptWorkInfoItem>
      
    </div>
    
    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore">
      <el-button type="primary" @click="loadMore">加载更多</el-button>
    </div>

  </div>
</el-dialog>
</template>

<script setup lang="ts">
import { ArrowLeft, Loading, Picture } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { postAIPublicIllustrationPosterDetail,postAIPublicWorkInfoPage,postAIToggleIllustrationPoster } from '../../../service/yapi';
import PublicCptWorkInfoItem from '~/components/public/CptWorkInfoItem.vue';
import { useAppStore } from "~/stores/app";

let app = useAppStore();

let { downloadByUrl } = app;
let downloadImage = (workInfo: any) => {
  downloadByUrl({ url: workInfo?.fileUrl, id: workInfo?.id, name: workInfo?.name });
}
const route = useRoute();
const router = useRouter();
const poetryId = route.params.id;

// 使用 useAsyncData 进行服务端渲染数据获取
const { data: poetryDetail, error, pending, refresh } = await useAsyncData(
  'poetryDetail',
  async () => {
    try {
      const response = await postAIPublicIllustrationPosterDetail({ id: poetryId });
      return response.data;
    } catch (err) {
      throw new Error('获取诗词详情失败，请稍后再试');
    }
  },
  {
    server: true,
    lazy: false,
    // 默认情况下，当用户导航到另一个路由时，asyncData 获取的数据将被保留。
    // 如果您不想保留，可以使用下面的选项
    watch: [route],
    // 在组件挂载之前获取数据
    immediate: true
  }
);
// 配图弹窗相关
const showPictureDialog = ref(false);
const pictureList = ref<any[]>([]);
const pagination = ref({
  total: 0,
  page: 1,
  size: 12
});

// 加载配图列表
const loadPictureList = async (isReset = false) => {
  if (isReset) {
    pagination.value = {
      total: 0,
      page: 1,
      size: 20
    };
    pictureList.value = [];
  }
  
  try {
    const res: any = await postAIPublicWorkInfoPage({
      order: "createTime",
      keyWord: "",
      page: pagination.value.page,
      size: pagination.value.size,
      topic: "古诗词配图"  // 指定主题为古诗配图
    });
    
    if (res.code === 1000) {
      const { list, pagination: paginationRes } = res.data;
      pagination.value = paginationRes;
      pictureList.value = [
        ...pictureList.value,
        ...list
      ];
    } else {
      ElMessage.warning(res.message);
    }
  } catch (error) {
    console.error("加载配图列表失败:", error);
    ElMessage.error("加载配图列表失败");
  }
};

// 加载更多图片
const loadMore = () => {
  if (pagination.value.page * pagination.value.size < pagination.value.total) {
    pagination.value.page += 1;
    loadPictureList();
  } else {
    ElMessage.info("没有更多配图了");
  }
};

// 计算是否有更多图片
const hasMore = computed(() => {
  return pagination.value.total > pagination.value.page * pagination.value.size;
});



// 当弹窗打开时加载图片
watch(showPictureDialog, (val) => {
  if (val) {
    loadPictureList(true);
  }
});

let toggleIluPoster = async (params: any) => {
  console.log("%c Line:258 🍩 params", "color:#ed9ec7", params);
  postAIToggleIllustrationPoster({
    psoterId:params.posterId,
    workinfoId:params.workInfo.id, 
  }).then((res: any) => {
    if (res.code == 1000) {
      ElMessage.success("操作成功");
      pictureList.value = pictureList.value.map((item: any) => {
        if (item.id == params.workInfo.id) {
          item.illustration = res.data.illustration;
        }
        return item;
      });
    } else {
      ElMessage.error(res.message);
    }
  });

}
definePageMeta({ auth: false });
const groupedWorkinfos = computed(() => {
  if (!poetryDetail.value?.workinfos) return [];
  
  const result = [];
  const works = poetryDetail.value.workinfos;
  
  for (let i = 0; i < works.length; i += 3) {
    result.push(works.slice(i, i + 3));
  }
  
  return result;
});

// 设置每个作品项的宽度
const workItemWidth = ref(230); // 可以根据实际需要调整
let showViewer = ref(false);
let srcList = ref<any>([])
let customerClick=(workInfo:any)=>{
  showViewer.value = true
  srcList.value = [workInfo.fileUrl]
}
let closePreivew = () => {
    showViewer.value = false;
  }
// 监听窗口大小变化，调整作品项宽度
onMounted(() => {
  window.scrollTo(0, 0);
  adjustWorkItemWidth();
  window.addEventListener('resize', adjustWorkItemWidth);
});

onUnmounted(() => {
  window.removeEventListener('resize', adjustWorkItemWidth);
});

// 调整作品项宽度的方法
const adjustWorkItemWidth = () => {
  const containerWidth = document.querySelector('.image-container')?.clientWidth || 800;
  // 留出间距，每个项目之间有20px的间距
  workItemWidth.value = Math.floor((containerWidth - 40) / 3);
  
  // 确保最小宽度
  if (workItemWidth.value < 180) workItemWidth.value = 180;
};
</script>

<style lang="scss" scoped>
.page-poetry-detail {
  background-color: #f9f6f0;
  max-width: 900px;
  margin: 0 auto;
  padding: 30px 20px 50px;
  min-height: 100vh;
  
  .el-input__wrapper.is-focus {
    box-shadow: 0 0 0 1px #73341d inset;
  }
  
  .el-button--primary {
    background: #8c7454;
    border-color: #73341d;
    
    &:hover {
      background: #73341d;
    }
  }
  
  .back-btn {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    cursor: pointer;
    width: fit-content;
    padding: 8px 16px;
    border-radius: 6px;
    background-color: #f5f7fc;
    transition: all 0.3s;
    font-family: "KaiTi", "楷体", serif;
    
    &:hover {
      background-color: #e8ecf7;
      transform: translateX(-5px);
    }
    
    span {
      margin-left: 6px;
      font-size: 15px;
    }
  }
  
  .poetry-detail-container {
    animation: fadeIn 0.6s ease-in-out;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      right: 0;
      width: 80px;
      height: 80px;
      background-size: contain;
      opacity: 0.1;
      pointer-events: none;
      z-index: -1;
      // background-image: url('/images/chinese-seal.png'); // 水印装饰
    }
  }
  
  .poetry-header {
    text-align: center;
    padding-bottom: 30px;
    margin-bottom: 30px;
    border-bottom: 1px solid #e8e0d0;
    position: relative;
    
    // 添加水墨装饰
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 30%;
      right: 30%;
      height: 1px;
      background: linear-gradient(to right, transparent, #c0b9a9, transparent);
    }
    
    .poetry-title {
      font-size: 36px;
      font-weight: 700;
      color: #73341d;
      margin-bottom: 15px;
      letter-spacing: 2px;
      font-family: "SimSun", "宋体", serif;
    }
    
    .poetry-meta {
      font-size: 16px;
      color: #8c7c64;
      font-family: "KaiTi", "楷体", serif;
      
      .dynasty {
        margin-right: 10px;
      }
      
      .author {
        font-weight: 500;
      }
    }
  }
  
  .section-title {
    font-size: 22px;
    font-weight: 600;
    color: #73341d;
    margin-bottom: 20px;
    padding-left: 12px;
    border-left: 4px solid #8c7454;
    font-family: "SimSun", "宋体", serif;
    letter-spacing: 1px;
  }
  
  .section-content {
    font-size: 16px;
    line-height: 1.8;
    color: #4a5568;
    font-family: "FangSong", "仿宋", serif;
    
    p {
      margin-bottom: 12px;
      text-indent: 2em;
    }
  }
  
  .poetry-content {
    margin-bottom: 40px;
    
    .poetry-original {
      font-size: 18px;
      line-height: 2;
      text-align: center;
      color: #333;
      background-color: #fcf9f2;
      padding: 30px 20px;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      font-family: "KaiTi", "楷体", serif;
      letter-spacing: 2px;
      border: 1px solid #e8e0d0;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        border: 1px dashed #d5c9b1;
        border-radius: 8px;
        pointer-events: none;
      }
      
      p {
        margin-bottom: 12px;
      }
    }
  }
  
  .poetry-image {
  margin-bottom: 40px;
  
  .image-container {
    display: flex;
    flex-direction: column;
    background-color: #f8f8f8;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid #e8e0d0;
    padding: 20px;
    
    .image-action {
      text-align: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px dashed #d5c9b1;
      
      .create-btn {
        background: #8c7454;
        border-color: #73341d;
        font-family: "KaiTi", "楷体", serif;
        letter-spacing: 1px;
        padding: 10px 20px;
        
        &:hover {
          background: #73341d;
        }
      }
    }
    
    .image-list {
      .poetry-carousel {
        background-color: #fcf9f2;
        border-radius: 8px;
        overflow: hidden;
        
        :deep(.el-carousel__arrow) {
          background-color: rgba(140, 116, 84, 0.7);
          
          &:hover {
            background-color: #8c7454;
          }
        }
        
        :deep(.el-carousel__indicators) {
          bottom: -25px;
        }
        
        .work-group {
          display: flex;
          justify-content: space-around;
          align-items: center;
          width: 100%;
          height: 100%;
          padding: 0 10px;
          
          .work-item {
            flex: 0 0 auto;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
            
            &:hover {
              transform: translateY(-5px);
            }
          }
        }
      }
      
      .no-image {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 300px;
        
        .el-empty {
          padding: 20px 0;
          
          p {
            margin-bottom: 15px;
            color: #8c7c64;
            font-family: "KaiTi", "楷体", serif;
          }
        }
      }
    }
    
    .image-placeholder,
    .image-error {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 400px;
      background-color: #f5f7fa;
      
      .el-icon {
        font-size: 24px;
        margin-bottom: 10px;
        color: #8c7c64;
      }
      
      span {
        color: #8c7c64;
        font-family: "KaiTi", "楷体", serif;
      }
    }
  }
  
  // 响应式调整
  @media (max-width: 768px) {
    .image-container {
      padding: 15px;
      
      .image-list {
        .poetry-carousel {
          height: 350px !important;
          
          .work-group {
            flex-wrap: wrap;
            overflow-y: auto;
            justify-content: center;
            
            .work-item {
              margin-bottom: 15px;
            }
          }
        }
      }
    }
  }
}
  
  .poetry-translation,
  .poetry-background,
  .poetry-appreciation {
    margin-bottom: 40px;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    border: 1px solid #e8e0d0;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 10px;
      right: 10px;
      width: 60px;
      height: 60px;
      opacity: 0.05;
      background-size: contain;
      pointer-events: none;
      // background-image: url('/images/chinese-pattern.png'); // 添加水墨装饰
    }
  }
  
  .loading-container {
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 12px;
    border: 1px solid #e8e0d0;
  }
  
  .error-container {
    padding: 40px 0;
    text-align: center;
    
    :deep(.el-empty__description p) {
      color: #8c7c64;
      font-family: "KaiTi", "楷体", serif;
    }
  }
  
  // 响应式布局调整
  @media (max-width: 768px) {
    padding: 20px 15px 40px;
    
    .poetry-header {
      padding-bottom: 20px;
      margin-bottom: 25px;
      
      .poetry-title {
        font-size: 28px;
      }
    }
    
    .section-title {
      font-size: 18px;
    }
    
    .poetry-content .poetry-original {
      padding: 20px 15px;
    }
    
    .poetry-image .image-container .el-image {
      height: 300px;
    }
    
    .poetry-translation,
    .poetry-background,
    .poetry-appreciation {
      padding: 15px;
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
